﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Reflection;

namespace SharePointUsers
{
    static class Program
    {
   

        #region Private Members
        private static string ToolVersion = GetToolVersion();
        private static string Welcome = "********************************************\n" +
                                        "*    Welcome to the SP User Manager v{0}   *\n" +
                                        "*     Programmed by Ahmed Farag - 2012     *\n" +
                                        "********************************************\n";
        static string ArgsHelp =    "To use SP User Manager type the following:\n\n" +
                                    "1- SPUManager.exe --> Starts the tool in windows\n" +
                                    "2- SPUManager.exe -Cmd --> Starts the tool in a command shell. Use the following parameters:\n" +
                                    "SPUManager.exe -Cmd -Path:\"SAVE_LOCATION\" [-Url:TARGET_SP_APP_URL|-AllFarm] [-NoPause] [-AppendDate]" +
                                    " [-IncludeSiteCollections] [-IncludeSubSites]\n\n" +
                                    "Parameters Guide:\n" +
                                    "-Cmd --> Turn on the command line mode.\n" +
                                    "-Path: --> [Required] The location where you want to store the exported users list.\n" +
                                    "-Url: --> [Optional] The Url of the SharePoint application to target for the users scan.\n" +
                                    "-AllFarm --> [Required if -Url is not specified]. Make the tool scan all web apps in the farm.\n" +
                                    "-NoPause --> [Optional] Suppresses the pause at the end of executing the command line.\n" +
                                    "-AppendDate --> [Optional] Appends the date and time to the supplied file name in the '-Path' param.\n" +
                                    "-IncludeSiteCollections --> [Optional] Creates a record for each site collection where the user exist.\n" +
                                    "-IncludeSubSites --> [Optional] Creates a record for each site where the user has been assigned an explicit permission.\n\n" +
                                    "Examples:\n"+
                                    "C:\\> SPUManager.exe\n"+
                                    "C:\\> SPUManager.exe -Cmd -Path:\"C:\\Users Reports\\CollabFarm.CSV\" -AllFarm\n"+
                                    "C:\\> SPUManager.exe -Cmd -Path:\"C:\\Users Reports\\CollabFarm.CSV\" -Url:http://Intranet.Corp.com -IncludeSiteCollections -IncludeSubSites\n\n" +
                                    "Note:\n"+
                                    "- This tool needs to run as administrator.\n"+
                                    "- To get a list of unique users in apps don't use '-IncludeSiteCollections' nor '-IncludeSubSites'\n";
        #endregion
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //Check if help needs to be displayed
            if (DoesArgumentExist("?", args) || 
                DoesArgumentExist("/?", args) ||
                DoesArgumentExist("/help", args) ||
                DoesArgumentExist("/GetHelp", args) ||
                DoesArgumentExist("-GetHelp", args))
            {
                AllocConsole();
                Console.WriteLine(ArgsHelp);
                Console.WriteLine("Press any key to exit ...");
                Console.ReadKey();
                return;
            }

            //Check if running in command line mode
            if (!DoesArgumentExist("-cmd", args))
                WinModeMain(args);
            else
            {
                AllocConsole();
                ConsoleModeMain(args);
            }
        }
        static void WinModeMain(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
        static void ConsoleModeMain(string[] args)
        {
            //Display welcome screen
            Console.WriteLine(Welcome, ToolVersion);
            if (ArgsAreValid(args))
            {
                //Prepare command control arg values 
                DateTime StartTime = DateTime.Now;
                bool SupressTerminationPause = DoesArgumentExist("-NoPause", args);
                bool AppendDateAndTime = DoesArgumentExist("-AppendDate", args);
                bool Verbose = DoesArgumentExist("-Verbose", args);

                //Prepare process control arg values
                bool AllFarm = DoesArgumentExist("-AllFarm", args);
                bool IncludeSiteCollections = DoesArgumentExist("-IncludeSiteCollections", args);
                bool IncludeSubSites = DoesArgumentExist("-IncludeSubSites", args);
                string TargetUrl = readStringArgumentValue("-url:", args);
                string TargetPath = readStringArgumentValue("-path:", args);

                bool UsersLoaded = false;
                //Execute Process
                SPUmanager spuManagerObj = new SPUmanager(IncludeSiteCollections, IncludeSubSites, Verbose);
                if (AllFarm)
                {
                    //Get user data for all apps in the farm
                    UsersLoaded = spuManagerObj.GetFarmUsers();
                }
                else
                {
                    //Get user data for the specified app url
                    UsersLoaded = spuManagerObj.GetWebAppUsers(TargetUrl);
                }
                if (UsersLoaded)
                {
                    //Save results to file
                    try
                    {
                        string FileName = TargetPath;
                        if (AppendDateAndTime)
                        {
                            string CurrentDateTime = StartTime.ToString("MM_dd_yy-HH_mm_ss");
                            FileName = AppendStringToFileName(TargetPath, CurrentDateTime);
                        }

                        spuManagerObj.WriteUserDataToCSVFile(FileName);
                        SPUmanager.WriteSuccess("Users have been written successfully to the selected file.");
                    }
                    catch (Exception Ex)
                    {
                        if (Verbose)
                            SPUmanager.WriteError("Error writing the users list to the disk.\nError details: {0}\nStack trace: {1}",
                            Ex.Message, Ex.StackTrace);
                        else
                            SPUmanager.WriteError("Error writing the users list to the disk.\nError details: {0}",
                            Ex.Message);
                    }
                }
                
                if (!SupressTerminationPause)
                {
                    Console.WriteLine("Press any key to exit ...");
                    Console.ReadKey();
                }
            }
            else
            {
                Console.WriteLine("Press any key to exit ...");
                Console.ReadKey();
            }
        }
        #region Arguments Commands
        static bool ArgsAreValid(string[] args)
        {
            if (DoesArgumentExist("?", args) || 
                DoesArgumentExist("/?", args) ||
                DoesArgumentExist("/help", args) ||
                DoesArgumentExist("/GetHelp", args) ||
                DoesArgumentExist("-GetHelp", args)
                )
            {
                Console.WriteLine(ArgsHelp);
                return false;
            }
            if (args.Length < 3)
            {
                Console.WriteLine("Invalid Arguments.\n\n" + ArgsHelp);
                return false;
            }
            if (string.IsNullOrEmpty(readStringArgumentValue("-path:", args)))//User didn't supply the path
            {
                Console.WriteLine("Missing -Path information.\n\n" + ArgsHelp);
                return false;
            }
            if (DoesArgumentExist("-path:", args) && string.IsNullOrEmpty(readStringArgumentValue("-path:", args))) //user supplied an empty path
            {
                Console.WriteLine("Invalid -Path information.\n\n" + ArgsHelp);
                return false;
            }
            if (!DoesArgumentExist("-AllFarm", args) && string.IsNullOrEmpty(readStringArgumentValue("-url:", args)))
            {
                Console.WriteLine("Supply the target app url or use the switch -AllFarm to include all apps.\n\n" + ArgsHelp);
                return false;
            }
            if (!DoesArgumentExist("-AllFarm", args) && string.IsNullOrEmpty(readStringArgumentValue("-url:", args)))
            {
                Console.WriteLine("Invalid target app information.\n\n" + ArgsHelp);
                return false;
            }
            return true;
        }
        static bool DoesArgumentExist(string arg, string[] args)
        {
            return GetArgumentIndex(arg, args) >= 0;
        }
        static int GetArgumentIndex(string arg, string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                if (string.Compare(args[i], arg, true) == 0) return i;
            }
            return -1;
        }
        static int GetArgumentIndexThatsStartsWith(string arg, string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].StartsWith(arg, StringComparison.OrdinalIgnoreCase)) return i;
            }
            return -1;
        }
        static string readStringArgumentValue(string arg, string[] args)
        {
            int argIndex = -1;
            if ((argIndex = GetArgumentIndexThatsStartsWith(arg, args)) >= 0)
            {
                if (args[argIndex].Length > arg.Length)
                {
                    return args[argIndex].Substring(arg.Length);
                }
            }
            return "";
        }
        static int readIntArgumentValue(string arg, string[] args, int defaultValue)
        {
            int value = defaultValue;
            int argIndex = -1;
            if ((argIndex = GetArgumentIndexThatsStartsWith(arg, args)) >= 0)
            {
                string[] values = args[argIndex].Split(':');
                if (values == null || values.Length != 2)
                    return value;
                int parsedValue = -1;
                if (!int.TryParse(values[1], out parsedValue))
                    return value;
                return parsedValue;
            }
            return value;
        }
        #endregion
        #region Auxilury Methods
        static string GetFileExtensionOnly(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return "";

            string[] FileParts = fileName.Split('.');
            if (FileParts == null || FileParts.Length < 2)
                return "";
            return FileParts[FileParts.Length - 1];
        }
        static string GetFileNameWithoutExtension(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return "";

            string Extension = GetFileExtensionOnly(fileName);
            return fileName.Replace("." + Extension, "");

        }
        static string GetFileNameWithoutExtension(string fileName,string Extension)
        {
            if (string.IsNullOrEmpty(fileName))
                return "";
            return fileName.Replace("." + Extension, "");
        }
        static string AppendStringToFileName(string fileName, string textToAppend)
        {
            string FileExtension = GetFileExtensionOnly(fileName);
            string FileNameOnly = GetFileNameWithoutExtension(fileName, FileExtension);

            return FileNameOnly + "_" + textToAppend + "." + FileExtension;
        }
        static string GetToolVersion()
        {
            string Version = "";

            try
            {
                Version CurentVersion = Assembly.GetEntryAssembly().GetName().Version;
                Version = CurentVersion.Major.ToString() + "." + CurentVersion.Minor;
            }
            catch
            {
                //No issue if we suppress the expection here
            }
            return Version;
        }
        #endregion
        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        private static extern bool AllocConsole(); 
    }
}
